package cn.edu.scnu.seckill.consumer;

import cn.edu.scnu.seckill.config.RabbitmqConfig;
import cn.edu.scnu.seckill.mapper.SecMapper;
import cn.edu.scnu.seckill.mapper.SucMapper;
import com.easymall.common.pojo.Success;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import redis.clients.jedis.JedisCluster;

import java.util.Date;
import java.util.List;

@Component
public class SeckillConsumer {
    @Autowired
    private SecMapper secMapper;
    @Autowired
    private SucMapper sucMapper;
    @Autowired
    private JedisCluster cluster;

    @RabbitListener(queues = RabbitmqConfig.queueName)
    public void processMsg(String msg) {
        if (!cluster.exists("opposeckill")) {
            System.out.println("该商品已经秒杀完毕！");
            return;
        }

        String rpop = cluster.rpop("opposeckill");
        if (rpop == null) {
            System.out.println("该商品已经秒杀完毕！");
            return;
        }


        String userId = msg.split("/")[0];
        Long seckillId = Long.parseLong(msg.split("/")[1]);
        Date nowTime = new Date();

        int result = secMapper.updateNum(seckillId, nowTime);
        if (result == 0) {
            System.out.println(userId + "用户秒杀失败");
            return;
        }

        Success success = new Success();
        success.setCreateTime(nowTime);
        success.setSeckillId(seckillId);
        success.setUserId(userId);
        success.setState(1);

        try {
            sucMapper.saveSuc(success);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("seckill/manage/{seckillId}/userPhone")
    public List<Success> querySuccess(@PathVariable Long seckillId) {
        return sucMapper.queryAllSuccess(seckillId);
    }
}